import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { AdvancedSearch, InputC, PrimaryC, PrimaryGhostC, FixedButtonC, DATA_ENTRY, codeType, ModalC, ContentPackage, TableC } from '../../../comps';

import ResultSearch from './resultSearch';
import AnalysisRecord from './components/analysisRecord';
import AddAnalysis from './components/addAnalysis';
import AbnormalData from './components/abnormalData';
import search from '../../../assets/busi/workStation/Barra/search.png';
import debounce from 'lodash/debounce';
import styles from './style.less';

@connect(({ valuationAnalysisM, loading, userM: user }) => ({
  valuationAnalysisM,
  tableLoading: loading.effects['valuationAnalysisM/getTableData'],
  saveAnalysisLoading: loading.effects['valuationAnalysisM/addAnalysis'],
  user,
}))
@Form.create()
export default class index extends PureComponent {
  constructor() {
    super();
    this.state = {
      pageInfo: {
        currentPage: 1, // 当前页
        numInPage: 10, // 分页条数
        total: 0, // 总页数
      },
      dataSource: [], // 表格数据
      columns: [], // 表头
      searchData: {}, // 查询条件
      dimensionList: [
        { value: '1', title: '产品' },
        { value: '2', title: '资产' },
      ],
      assetTypeList: [
        { value: '01', title: '资产管理计划' },
        { value: '02', title: '委外资产' },
        { value: '03', title: '基金' },
      ],
      assetDict: {
        '01': 'zgtzptPlan',
        '02': 'outsourcing',
        '03': 'smjj',
      },
      assetType: '01',
      formReset: false, // 是否重置

      infoDetail: undefined, // 当前操作的估值解析
      infoShow: false, // 是否展示解析结果
      addVisiable: false, // 新增模态框
      recordVisiable: false, // 申请记录模态框
      sortedInfo: null, // 排序对象
      abnormalVisiable: false, // 批量申请异常查询Modal
    };
    // 绑定lodash的防抖函数，避免频繁搜索的情况
    this.searchOnChange = debounce(this.searchOnChange, 500);
  }

  componentDidMount() {
    if (this.props.pageType == '2') {
      this.props.onRef && this.props.onRef(this);
      // 穿透工作台
      if (this.props.trandingCode && this.props.trandingName) {
        this.setState(
          {
            value: this.props.trandingCode,
          },
          () => {
            this.props.form.setFieldsValue({
              value: `${this.props.trandingCode}-${this.props.trandingName}`,
            });
            this.getTableData();
          },
        );
      } else {
        this.getTableData();
      }
    } else {
      // 页面判断是否跳转过来
      if (sessionStorage.getItem('GZJX_pageJump')) {
        this.sessionStorageAction();
        return;
      }
      this.getTableData();
      this.props.dispatch({
        type: 'valuationAnalysisM/valuationCheckProductInfo',
        payload: {
          createdBy: localStorage.getItem('antd-pro-userId'),
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE', 'VALUATION_TABLE_ANALYSIS_MODE'], // 仅估值解析模式、指令模式、簿记模式的产品可选
        },
      });
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (sessionStorage.getItem('GZJX_pageJump')) {
      this.sessionStorageAction();
      return;
    }
    if (this.props.pageType == '2') {
      // 穿透工作台
      if (this.props.trandingCode != nextProps.trandingCode) {
        console.log(`${nextProps.trandingCode}-${nextProps.trandingName}`);
        this.setState(
          {
            value: nextProps.trandingCode,
          },
          () => {
            this.props.form.setFieldsValue({
              value: `${this.props.trandingCode}-${this.props.trandingName}`,
            });
            this.getTableData();
          },
        );
      }
    }
  }

  // 接收sessionStorage传递参数处理
  sessionStorageAction = () => {
    const searchData = JSON.parse(sessionStorage.getItem('GZJX_pageJump'));
    sessionStorage.removeItem('GZJX_pageJump');
    this.setState(
      {
        pageInfo: {
          currentPage: 1, // 当前页
          numInPage: 10, // 分页条数
          total: 0, // 总页数
        },
        searchData: {
          ...searchData,
        },
        dimension: searchData.dimension,
        assetType: searchData.assetType,
      },
      () => {
        this.getTableData();
        this.GZJXRef?.props.form.setFieldsValue({
          dimension: searchData.dimension,
          assetType: searchData.assetType,
        });
        setTimeout(() => {
          this[`securityCodeRef${searchData.assetType}`]?.setSelect(searchData.code);
        }, 100);
      },
    );
  };

  // 点击查询
  formQuery = (_data) => {
    const {
      pageInfo: { numInPage },
    } = this.state;
    delete _data.exchangeCode;
    if (_data.dimension == '1') {
      _data.assetType = '00';
    }
    this.setState(
      {
        formReset: false,
        searchData: { ..._data },
        pageInfo: {
          currentPage: 1, // 当前页
          numInPage, // 分页条数
        },
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 重置
  onClear = () => {
    this.setState({
      formReset: true,
      dimension: undefined,
      assetType: '01',
      sortedInfo: null, // 排序对象
    });
  };

  // 查询维度/资产类型变化
  formFieldChange = (type, e) => {
    this.setState(
      {
        [type]: e || undefined,
      },
      () => {
        this.GZJXRef.props.form.setFieldsValue({
          code: undefined,
        });
      },
    );
  };

  // 估值解析--表单查询
  renderForm = () => {
    const { dimensionList, assetTypeList, assetDict, dimension, assetType } = this.state;
    const {
      valuationAnalysisM: { productList = [] },
    } = this.props;
    return (
      <AdvancedSearch
        dataSource={[
          {
            dataIndex: 'dimension',
            title: '解析维度',
            type: DATA_ENTRY.SELECT,
            dataSource: dimensionList,
            onChange: (e) => this.formFieldChange('dimension', e),
            showSearch: false,
            allowClear: true,
          },
          {
            hide: !(dimension == '1'),
            dataIndex: 'code',
            title: '产品代码',
            type: DATA_ENTRY.SELECT,
            dataSource: productList,
            filterOption: (input, option) => {
              // 模糊搜索value 和 label
              return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
            },
            allowClear: true,
          },
          {
            hide: !(dimension == '2'),
            dataIndex: 'assetType',
            title: '资产类型',
            type: DATA_ENTRY.SELECT,
            dataSource: assetTypeList,
            initialValue: assetType,
            onChange: (e) => this.formFieldChange('assetType', e),
            allowClear: false,
          },
          {
            hide: !(dimension == '2' && assetType == '01'), // 资产管理计划
            dataIndex: 'code',
            title: '资产代码',
            type: DATA_ENTRY.SECURITIESCODE,
            codeType: codeType[assetDict[assetType]],
            onRef: (ref) => (this[`securityCodeRef${assetType}`] = ref),
            allowClear: true,
          },
          {
            hide: !(dimension == '2' && assetType == '02'), // 委外投资
            dataIndex: 'code',
            title: '资产代码',
            type: DATA_ENTRY.SECURITIESCODE,
            codeType: codeType[assetDict[assetType]],
            onRef: (ref) => (this[`securityCodeRef${assetType}`] = ref),
            allowClear: true,
          },
          {
            hide: !(dimension == '2' && assetType == '03'), // 私募基金
            dataIndex: 'code',
            title: '资产代码',
            type: DATA_ENTRY.SECURITIESCODE,
            codeType: codeType[assetDict[assetType]],
            onRef: (ref) => (this[`securityCodeRef${assetType}`] = ref),
            allowClear: true,
          },
        ]}
        onQuery={this.formQuery}
        onClear={this.onClear}
        onRef={(ref) => (this.GZJXRef = ref)}
      />
    );
  };

  // 穿透工作台--表单查询
  stationForm = () => {
    const {} = this.state;
    const {} = this.props;
    return (
      <div className={styles.searchCont}>
        <InputC
          form={this.props.form}
          dataIndex='value'
          placeholder='请输入产品名称或代码进行模糊搜索'
          suffix={
            <div className='flotRight'>
              <img src={search}></img>
            </div>
          }
          onChange={(e) => {
            e.persist(); // 以异步方式访问事件属性，调用 event.persist()，阻止react合成事件，允许保留对事件的引用。
            this.searchOnChange(e);
          }}
          style={{ width: '208px' }}
        />
        <div>
          <PrimaryC title='新增' onClick={() => this.analysisOperate('add')} />
          <PrimaryC title='批量申请异常查询' style={{ marginLeft: '16px' }} onClick={() => this.setState({ abnormalVisiable: true })} />
        </div>
      </div>
    );
  };

  // 穿透工作台--响应搜索框变化
  searchOnChange = (e) => {
    this.setState(
      {
        value: e.target?.value,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 获取表格数据
  getTableData = () => {
    const that = this;
    const {
      searchData,
      pageInfo: { currentPage, numInPage },
      sortedInfo,
      value,
      assetType,
    } = this.state;
    const { dispatch, pageType, dimension } = this.props;
    const obj = {};
    if (sortedInfo?.order) {
      obj.columnKey = sortedInfo?.columnKey;
      obj.order = sortedInfo?.order;
    }
    const data = {
      ...searchData,
      currentPage,
      numInPage,
      ...obj,
    };
    if (pageType == '2') {
      data.value = value || null; // 模糊查询
    }
    dispatch({
      type: 'valuationAnalysisM/getTableData',
      payload: data,
      callback: (type, data) => {
        if (type == 'success') {
          that.setState({
            columns: data.columns,
            dataSource: data.dataSource,
            pageInfo: data.pageInfo,
          });
        }
      },
    });
  };

  // 表格
  renderTable = () => {
    const { dataSource, columns, pageInfo, assetTypeList } = this.state;
    const { tableLoading, pageType } = this.props;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo || {};
    let columnsNew = JSON.parse(JSON.stringify(columns));
    if (columnsNew.length) {
      columnsNew.forEach((item) => {
        if (item.key == 'code' || item.key == 'assetType' || item.key == 'applicantTime' || item.key == 'endDate') {
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
        }
        if (pageType == '2') {
          if (item.key == 'code' || item.key == 'name') {
            item.type = 'maxContent';
          }
        }
        if (item.key === 'dimension') {
          item.render = (text) => {
            return text == '1' ? '产品' : '资产';
          };
        }
        if (item.key === 'assetType') {
          item.render = (text) => {
            return assetTypeList.filter((item) => item.value === text)[0]?.title || '--';
          };
        }
        if (item.key == 'applicantTime' || item.key == 'endDate') {
          item.type = 'date';
        }
      });

      columnsNew.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        width: 210,
        fixed: 'right',
        operates: [
          {
            title: '新增解析',
            onClick: (record) => {
              this.analysisOperate('add', record);
            },
          },
          {
            title: '申请记录',
            onClick: (record) => {
              this.analysisOperate('record', record);
            },
          },
          {
            title: '结果查询',
            onClick: (record) => {
              this.analysisOperate('info', record);
            },
          },
        ],
      });
    } else {
      columnsNew = [];
    }
    return (
      <div style={{ marginTop: '16px' }}>
        <TableC
          size={pageType == '2' ? 'small' : undefined}
          columns={columnsNew}
          dataSource={dataSource}
          loading={tableLoading}
          onChange={this.tableOnChange}
          current={pageInfo.currentPage}
          total={pageInfo.total}
          pageSize={pageInfo.numInPage}
          selfScrollY={true}
          scroll={pageType == '2' ? { x: 'max-content', y: 330 } : {}}
          rowKey='id'
        />
      </div>
    );
  };

  // 表格页码变化
  tableOnChange = (pagination, filters, sorter) => {
    const { pageInfo, formReset } = this.state;
    this.setState(
      {
        sortedInfo: sorter,
      },
      () => {
        if (formReset) {
          message.warning('您已重置查询字段，请设置条件后执行查询');
          return;
        }
        this.setState(
          {
            pageInfo: {
              ...pageInfo,
              currentPage: pagination.current, // 当前页
              numInPage: pagination.pageSize, // 分页条数
            },
          },
          () => {
            this.getTableData();
          },
        );
      },
    );
  };

  // add - 新增/新增解析   info - 解析结果 record - 申请记录
  analysisOperate = (type, record) => {
    const { pageType } = this.props;
    if (type === 'add') {
      this.setState({
        addVisiable: true,
        infoDetail: record || undefined,
      });
    } else if (type == 'record') {
      this.setState({
        recordVisiable: true,
        infoDetail: record,
      });
    } else if (type === 'info') {
      if (pageType != '2') {
        this.setState({
          infoShow: true,
          infoDetail: record,
        });
      } else {
        this.setState({
          infoDetail: record,
        });
        this.props.changeResultPage(false, 3, record);
      }
    }
  };

  // 点击确认
  addAnalysisOk = () => {
    const that = this;
    const { infoDetail } = this.state;
    const formObj = this.addAnalysisRef?.getInfo();
    let haveRar = false; // 上传文件是否包含压缩包
    if (!formObj) {
      return;
    }
    const formData = new FormData();
    formObj.file.map((item) => {
      // 判断上传文件是否包含压缩包，有压缩包文件时，仅支持单个文件上传
      const flieArr = item.name?.split('.');
      const suffix = flieArr[flieArr?.length - 1];
      if (['rar', 'zip'].find((x) => x === suffix)) {
        haveRar = true;
      }
      formData.append('fileId', item?.value);
    });
    if (haveRar && formObj.file.length > 1) {
      message.warning('压缩包文件仅支持单个上传！');
      return;
    }
    formData.append('dimension', formObj.dimension);
    if (formObj.isStandard) {
      formData.append('isStandard', formObj.isStandard);
    }
    if (infoDetail) {
      if (infoDetail.code) {
        formData.append('code', infoDetail.code);
        formData.append('codeId', infoDetail.codeId);
        formData.append('codeName', infoDetail.name);
      }
      formData.append('id', infoDetail.id);
      formData.append('assetType', infoDetail.assetType || '00');
    } else {
      if (formObj.code) {
        formData.append('code', formObj.code);
        formData.append('codeId', formObj.codeId);
        formData.append('codeName', formObj.codeName);
      }
      formData.append('assetType', formObj.assetType || '00');
    }
    this.props.dispatch({
      type: 'valuationAnalysisM/addAnalysis',
      payload: formData,
      callback: (msg) => {
        if (msg === 'success') {
          that.getTableData();
          that.setState({
            addVisiable: false,
            infoDetail: undefined,
          });
        }
      },
    });
  };

  changePage = () => {
    this.setState({
      infoShow: false,
      infoDetail: undefined,
    });
  };

  render() {
    const { infoShow, infoDetail, addVisiable, recordVisiable, abnormalVisiable } = this.state;
    const { saveAnalysisLoading, pageType } = this.props;
    return (
      <>
        {!infoShow ? (
          pageType == '2' ? (
            <div>
              {this.stationForm()}
              {this.renderTable()}
            </div>
          ) : (
            <ContentPackage
              title='估值解析'
              contentHtml={
                <>
                  <div>
                    {this.renderForm()}
                    <div style={{ marginTop: '20px' }}>
                      <PrimaryC title='新增' onClick={() => this.analysisOperate('add')} />
                      <PrimaryC title='批量申请异常查询' style={{ marginLeft: '16px' }} onClick={() => this.setState({ abnormalVisiable: true })} />
                    </div>
                    {this.renderTable()}
                  </div>
                </>
              }
            />
          )
        ) : (
          ''
        )}
        <ModalC
          title={'新增'}
          destroyOnClose={true}
          maskClosable={false}
          visible={addVisiable}
          width={850}
          onOk={this.addAnalysisOk}
          cancelButtonProps={{ loading: saveAnalysisLoading }}
          confirmLoading={saveAnalysisLoading}
          onCancel={() => {
            this.setState({
              addVisiable: false,
              infoDetail: undefined,
            });
          }}
          children={<AddAnalysis infoDetail={infoDetail} onRef={(ref) => (this.addAnalysisRef = ref)} />}
        />

        <ModalC
          title={'申请记录'}
          visible={recordVisiable}
          destroyOnClose={true}
          width={1000}
          footer={null}
          onCancel={() => {
            this.setState({
              recordVisiable: false,
              infoDetail: undefined,
            });
          }}
          children={<AnalysisRecord infoDetail={infoDetail} />}
        />

        <ModalC
          title={'批量申请异常查询'}
          visible={abnormalVisiable}
          destroyOnClose={true}
          width={1000}
          footer={null}
          onCancel={() => {
            this.setState({
              abnormalVisiable: false,
            });
          }}
          children={<AbnormalData />}
        />
        {infoDetail?.id && infoShow && pageType != '2' && <ResultSearch infoDetail={infoDetail} changeResultPage={this.changePage} />}
      </>
    );
  }
}
